<script setup>
import axios from 'axios'
import { ref, onMounted, onUnmounted, inject } from 'vue'
import { provinceNameMap, provinceCenterMap, nameToPinyin } from '@/utils/mapUtils'
import { exportEmploymentExcelService, getEmploymentAnalysisService } from '@/api/dataAnalysis'
import { getGraduateYears, getGraduateColleges, getGraduateMajors } from '@/api/graduate'
import { useTransition } from '@vueuse/core'
import { Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
const echarts = inject('echarts')
// DOM 引用和图表实例
const chartRef = ref(null)
const myChart = ref(null)
const responseResult = ref(null)
const currentMapName = ref('china')
const mapData = {}
// 样式配置
const initOption = {
  title: {
    text: '▎ 毕业生就业分布',
    left: 20,
    top: 20,
    textStyle: {
      color: '#333',
      fontSize: 18
    }
  },
  geo: {
    map: 'china',
    roam: true,
    center: undefined,
    itemStyle: {
      areaColor: '#2ebdff',
      borderColor: '#333',
      borderWidth: 0.5
    },
    emphasis: {
      itemStyle: {
        areaColor: '#4499FF'
      }
    }
  },
  visualMap: {
    /*     min: 0,
        max: 10,
        left: '5%',
        bottom: '5%',
        inRange: {
          color: ['#e88f21', '#e43c30']
        },
        textStyle: {
          color: '#666'
        },
        calculable: true */
    min: 0,
    max: 10,
    left: '5%',
    bottom: '5%',
    text: ['高', '低'], // 添加高低指示
    textGap: 10, // 文字与滑块间距
    inRange: {
      color: ['#e88f21', '#e43c30'] // 更柔和的渐变色
    },
    textStyle: {
      color: '#333',
      fontSize: 12,
      fontWeight: 'bold' // 加粗文字
    },
    calculable: true,
    // 添加单位说明
    seriesIndex: [0],
    formatter: function (value) {
      return Math.round(value) + '人' // 添加单位
    },
    // 设置高亮状态样式
    emphasis: {
      textStyle: {
        color: '#000', // 悬停时使用更深的颜色
        opacity: 1 // 确保完全不透明
      }
    },
    // 更美观的控制器样式
    itemWidth: 20,
    itemHeight: 120,
    borderWidth: 1,
    borderColor: '#ddd',
    backgroundColor: '#f9f9f9',
    precision: 0 // 强制使用整数精度
  },
  tooltip: {
    trigger: 'item',
    formatter: (params) => {
      return `${params.name}: ${params.value ? params.value : 0}`
    }
  }
}

const provinceData = ref([]) //中国地图上省份分布数据
const currentCityArrayData = ref([]) // 存储当前省份的城市数据
// 使用普通对象作为缓存，因为：
// 1. 数据量不大(省份数量有限)
// 2. 不需要响应式变化(缓存数据不会动态变化)
// 3. 访问性能足够(比Map稍快)
const provinceCitiesCacheMap = {}

// 初始化图表
const initChart = async () => {
  // 初始化 ECharts 实例
  myChart.value = echarts.init(chartRef.value)

  // 加载中国地图
  const { data: chinaData } = await axios.get('/map-data/china.json')
  // console.log('chinaData', chinaData);
  echarts.registerMap('china', chinaData)

  // 设置初始配置
  myChart.value.setOption(initOption)
  console.log('中国地图设置完毕')

  // 绑定双击事件
  chartRef.value.ondblclick = () => {
    if (currentMapName.value !== 'china') {
      currentMapName.value = 'china'
      // initOption.geo.map = 'china'
      myChart.value.dispatchAction({
        type: 'downplay', // 清除所有高亮状态
        seriesIndex: 0
      })

      myChart.value.setOption({
        geo: {
          map: 'china',
          center: [108.55, 34.32] // 设置中心点（经度, 纬度）
        },
        series: [
          {
            type: 'map',
            geoIndex: 0
          }
        ]
      })

      setProvinceDistributionData()
    }
  }

  // 绑定点击事件// 监听地图点击事件
  myChart.value.on('click', async (params) => {
    // 如果不是中国地图或点击了南海诸岛，则不处理
    if (currentMapName.value !== 'china' || params.name === '南海诸岛') {
      return // 跳过非中国区域和南海诸岛的特殊处理
    }

    const provinceName = params.name // 获取点击的省份名称,如安徽
    console.log('点击了省份', provinceName) // 调试日志：打印点击的省份名
    // 将中文省份名转换为拼音,因为矢量地图json文件名按拼音区分
    const mapName = nameToPinyin[provinceName] || provinceName // 使用拼音映射表转换或保留原值
    await loadProvinceMapData(mapName) // 异步加载省份矢量地图数据
    currentMapName.value = mapName // 更新当前地图名称,如anhui

    // 使用缓存的城市数据,如果缓存中没有，则从响应数据中获取,使用拼音名称作为缓存键
    if (!provinceCitiesCacheMap[mapName]) {
      // 检查是否已有缓存
      const provinceData = responseResult.value?.provinceDistribution?.find(
        (p) => provinceNameMap[p.name] === provinceName // 匹配省份数据
      )
      provinceCitiesCacheMap[mapName] = provinceData?.cities || [] // 缓存城市数据或空数组
    }
    currentCityArrayData.value = provinceCitiesCacheMap[mapName] // 设置当前城市数据

    // 3. 更新地图显示
    const center = provinceCenterMap[provinceName] // 获取该省份的中心坐标
    console.log('设置省份数据 - 中心点:', center) // 调试日志：打印中心点坐标
    myChart.value.setOption({
      // 更新地图配置
      geo: {
        map: mapName, // 设置新地图名称
        center // 设置地图中心点
      },
      series: [
        {
          type: 'map', // 地图类型
          geoIndex: 0, // 使用第一个geo配置
          zoom: 1.2, // 设置缩放级别
          data: currentCityArrayData.value // 设置城市数据
        }
      ]
    })
  })
}
//只设置城市数据 series: ，不设置地图
const setProvinceInnerCitiesData = () => {
  myChart.value.setOption({
    series: [
      {
        type: 'map',
        geoIndex: 0,
        data: currentCityArrayData.value
      }
    ]
  })
}

// 修改为使用普通ref而不是直接使用useTransition
const totalGraduates = ref(0)
const employed = ref(0)
const unemployed = ref(0)
const furtherStudy = ref(0)
const employmentRate = ref(0)
const studyRate = ref(0)

// 创建过渡效果
const animatedTotalGraduates = useTransition(totalGraduates, { duration: 1000 })
const animatedEmployed = useTransition(employed, { duration: 1000 })
const animatedUnemployed = useTransition(unemployed, { duration: 1000 })
const animatedFurtherStudy = useTransition(furtherStudy, { duration: 1000 })
const animatedEmploymentRate = useTransition(employmentRate, { duration: 1000 })
const animatedStudyRate = useTransition(studyRate, { duration: 1000 })

const getEmploymentAnalysisData = async (params) => {
  console.log('请求参数', params)
  const { data: provinceDistributedData } = await getEmploymentAnalysisService(params)
  responseResult.value = provinceDistributedData
  console.log('返回数据', responseResult.value)
  // const { data: statusArray } = await getEmploymentStatusService(params)
  // console.log('获取就业状态数据成功', statusArray);

  // 更新过渡值
  totalGraduates.value = provinceDistributedData.total?.totalGraduates || 0
  employed.value = provinceDistributedData.total?.employed || 0
  unemployed.value = provinceDistributedData.total?.unemployed || 0
  furtherStudy.value = provinceDistributedData.total?.furtherStudy || 0

  // // 计算就业率和深造率
  // if (provinceDistributedData.total) {
  //   const total = provinceDistributedData.total.totalGraduates || 1 // 避免除以0
  //   provinceDistributedData.total.employmentRate =
  //     Math.round((provinceDistributedData.total.employed / total) * 10000) / 100 // 保留2位小数
  //   provinceDistributedData.total.studyRate =
  //     Math.round((provinceDistributedData.total.furtherStudy / total) * 10000) / 100
  // }
  if (provinceDistributedData.total) {
    const total = provinceDistributedData.total.totalGraduates || 1
    employmentRate.value =
      Math.round((provinceDistributedData.total.employed / total) * 10000) / 100
    studyRate.value = Math.round((provinceDistributedData.total.furtherStudy / total) * 10000) / 100
  }

  provinceData.value = provinceDistributedData.provinceDistribution.map((p) => ({
    name: provinceNameMap[p.name] || p.name, // 使用省份映射表转换名称，若无映射则保留原名
    value: p.value // 保留原始数值
  }))
  console.log('已经预处理了数据') // 调试日志：数据预处理完成
  setProvinceDistributionData() // 调用函数设置省份分布数据
}

// 加载中国地图的省份分布数据
const setProvinceDistributionData = () => {
  console.log('设置中国地图的数据') // 调试日志：开始设置地图数据
  myChart.value.setOption({
    series: [
      {
        type: 'map', // 图表类型为地图
        geoIndex: 0, // 使用第一个地理坐标系
        data: provinceData.value // 绑定预处理后的省份数据
      }
    ]
  })
}

// 加载具体省份地图数据
const loadProvinceMapData = async (mapName) => {
  if (!mapData[mapName]) {
    try {
      const { data } = await axios.get(`/map-data/province/${mapName}.json`)
      console.log('加载省份地图数据', mapName, data)
      echarts.registerMap(mapName, data)
      mapData[mapName] = data
      console.log('地图省份数据已加载')
    } catch (error) {
      console.error('具体省份地图加载失败:', error)
    }
  }
}

onUnmounted(() => {
  // 添加移除事件监听
  window.removeEventListener('resize', screenAdapter)
  myChart?.value.dispose()
})

const years = ref([])
const colleges = ref([])
const majors = ref([])
const selectedYear = ref('')
const selectedCollege = ref('')
const selectedMajor = ref('')

// 页面加载时获取年份数据
onMounted(async () => {
  console.log('即将初始化图表')
  initChart()
  // 获取年份数据
  const { data } = await getGraduateYears()
  years.value = data
  selectedYear.value = years.value[0]
  // 添加窗口resize监听
  window.addEventListener('resize', screenAdapter)
  // 初始化时立即执行一次适配
  screenAdapter()
  if (selectedYear.value) {
    const { data } = await getGraduateColleges(selectedYear.value)
    colleges.value = data
  } else {
    colleges.value = []
  }
  await getEmploymentAnalysisData({
    year: selectedYear.value
  })
})
// 添加自适应方法
const screenAdapter = () => {
  if (!chartRef.value || !myChart.value) {
    return
  }

  const containerWidth = chartRef.value.offsetWidth
  const titleFontSize = (containerWidth / 100) * 3.6

  console.log('省份数据', provinceData.value)
  const adapterOption = {
    title: {
      textStyle: {
        fontSize: titleFontSize
      }
    },
    visualMap: {
      itemWidth: titleFontSize / 2,
      itemHeight: titleFontSize * 4,
      textStyle: {
        fontSize: titleFontSize / 2
      }
    }
  }

  myChart.value.setOption(adapterOption)
  myChart.value.resize()
  if (currentMapName.value !== 'china') {
    //如果是省份地图
    setProvinceInnerCitiesData(currentMapName.value)
  } else {
    setProvinceDistributionData()
  }
}
// 年份变化时获取学院数据
const handleYearChange = async () => {
  selectedCollege.value = '' //空字符串时为假
  selectedMajor.value = ''
  majors.value = []
  console.log('年份变化', selectedYear.value)

  await getEmploymentAnalysisData({
    year: selectedYear.value
  })
  // 手动触发双击事件
  chartRef.value.ondblclick()

  if (selectedYear.value) {
    const { data } = await getGraduateColleges(selectedYear.value)
    colleges.value = data
  } else {
    colleges.value = []
  }
}

// 学院变化时获取专业数据
const handleCollegeChange = async () => {
  selectedMajor.value = ''

  console.log('学院变化', selectedCollege.value)
  if (selectedCollege.value) {
    await getEmploymentAnalysisData({
      year: selectedYear.value,
      college: selectedCollege.value
    })
    chartRef.value.ondblclick()
  }

  if (selectedYear.value && selectedCollege.value) {
    const { data } = await getGraduateMajors(selectedYear.value, selectedCollege.value)
    majors.value = data
  } else {
    majors.value = []
  }
}
const handleMajorChange = async () => {
  console.log('专业变化', selectedMajor.value)
  if (selectedMajor.value) {
    await getEmploymentAnalysisData({
      year: selectedYear.value,
      college: selectedCollege.value,
      major: selectedMajor.value
    })
    chartRef.value.ondblclick()
  }
}

// 添加重置方法
const handleReset = async () => {
  selectedYear.value = years.value[0]
  selectedCollege.value = ''
  selectedMajor.value = ''
  majors.value = []
  await getEmploymentAnalysisData({
    year: selectedYear.value
  })
  chartRef.value.ondblclick()
}

const isExporting = ref(false)

const handleExport = async () => {
  if (isExporting.value) {
    return
  }

  isExporting.value = true
  try {
    // 直接获取 blob 数据
    const response = await exportEmploymentExcelService() //注意没有解构赋值Data

    // 创建文件名（可以从响应头获取）
    const contentDisposition = response.headers['content-disposition']
    const fileName = contentDisposition
      ? contentDisposition.split('filename=')[1]
      : 'employment_data.xlsx'

    // 创建下载链接
    const blob = new Blob([response.data])
    const downloadUrl = URL.createObjectURL(blob)
    const anchor = document.createElement('a')
    anchor.href = downloadUrl
    anchor.download = decodeURIComponent(fileName)
    document.body.appendChild(anchor)
    anchor.click()
    document.body.removeChild(anchor)
    URL.revokeObjectURL(downloadUrl)

    ElMessage.success('导出成功')
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '导出失败'
    ElMessage.error(errorMessage)
    console.error('导出错误:', error)
  } finally {
    isExporting.value = false
  }
}
</script>

<template>
  <!-- 过滤筛选 -->
  <div class="filter-bar">
    <div class="filter-item">
      <span class="filter-label word-1">毕业年份：</span>
      <el-select
        style="width: 150px"
        v-model="selectedYear"
        placeholder="请选择毕业年份"
        @change="handleYearChange"
      >
        <!-- <el-option label="2023届" value="2023" />
        <el-option label="2022届" value="2022" /> -->
        <el-option v-for="year in years" :key="year" :label="year" :value="year" />
      </el-select>
    </div>

    <div class="filter-item">
      <span class="filter-label word-1">学院：</span>
      <el-select
        v-model="selectedCollege"
        placeholder="请选择学院"
        :disabled="!selectedYear"
        @change="handleCollegeChange"
        style="width: 150px"
      >
        <!-- <el-option label="计算机学院" value="计算机" />
        <el-option label="经管学院" value="经管" /> -->
        <el-option v-for="college in colleges" :key="college" :label="college" :value="college" />
      </el-select>
    </div>

    <div class="filter-item">
      <span class="filter-label word-1">专业：</span>
      <el-select
        v-model="selectedMajor"
        placeholder="请选择专业"
        :disabled="!selectedCollege"
        @change="handleMajorChange"
        style="width: 150px"
      >
        <!-- <el-option label="软件工程" value="软件" />
        <el-option label="网络工程" value="网络" /> -->
        <el-option v-for="major in majors" :key="major" :label="major" :value="major" />
      </el-select>
    </div>

    <!-- 添加重置按钮 -->
    <el-col :span="6" class="button-group">
      <el-button type="default" @click="handleReset">重置</el-button>
      <el-button
        type="primary"
        @click="handleExport"
        :loading="isExporting"
        :disabled="isExporting"
      >
        <template #icon>
          <el-icon><Download /></el-icon>
        </template>
        {{ isExporting ? '导出中...' : '导出Excel' }}
      </el-button>
    </el-col>
  </div>

  <div class="summary-text" v-if="false">
    总计毕业人数共
    <span class="highlight">{{ responseResult?.total?.totalGraduates || 0 }}</span> 人， 其中
    <el-tooltip effect="light" placement="top" content="就业率 = 已就业人数 / 总毕业人数 × 100%">
      <span class="highlight">{{ responseResult?.total?.employed || 0 }}</span>
    </el-tooltip>
    人已就业 (就业率:
    <span class="highlight">{{ responseResult?.total?.employmentRate || 0 }}%</span>)，
    <span class="highlight">{{ responseResult?.total?.unemployed || 0 }}</span> 人待业，
    <el-tooltip effect="light" placement="top" content="深造率 = 深造人数 / 总毕业人数 × 100%">
      <span class="highlight">{{ responseResult?.total?.furtherStudy || 0 }}</span>
    </el-tooltip>
    人深造 (深造率: <span class="highlight">{{ responseResult?.total?.studyRate || 0 }}%</span>)。
  </div>
  <div class="summary-container" v-if="false">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-statistic title="总毕业人数" :value="responseResult?.total?.totalGraduates || 0" />
      </el-col>
      <el-col :span="6">
        <el-statistic title="已就业人数" :value="responseResult?.total?.employed || 0">
          <template #title>
            <el-tooltip
              effect="light"
              placement="top"
              content="就业率 = 已就业人数 / 总毕业人数 × 100%"
            >
              <span>已就业人数</span>
            </el-tooltip>
          </template>
          <template #suffix>
            <span class="rate-text">({{ responseResult?.total?.employmentRate || 0 }}%)</span>
          </template>
        </el-statistic>
      </el-col>
      <el-col :span="6">
        <el-statistic title="待业人数" :value="responseResult?.total?.unemployed || 0" />
      </el-col>
      <el-col :span="6">
        <el-statistic title="深造人数" :value="responseResult?.total?.furtherStudy || 0">
          <template #title>
            <el-tooltip
              effect="light"
              placement="top"
              content="深造率 = 深造人数 / 总毕业人数 × 100%"
            >
              <span>深造人数</span>
            </el-tooltip>
          </template>
          <template #suffix>
            <span class="rate-text">({{ responseResult?.total?.studyRate || 0 }}%)</span>
          </template>
        </el-statistic>
      </el-col>
    </el-row>
  </div>
  <div class="summary-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-statistic title="总毕业人数" :value="Math.round(animatedTotalGraduates)" />
      </el-col>
      <el-col :span="6">
        <el-statistic title="已就业人数" :value="Math.round(animatedEmployed)">
          <template #title>
            <el-tooltip
              effect="light"
              placement="top"
              content="就业率 = 已就业人数 / 总毕业人数 × 100%"
            >
              <span>已就业人数</span>
            </el-tooltip>
          </template>
          <template #suffix>
            <span class="rate-text">({{ animatedEmploymentRate.toFixed(2) }}%)</span>
          </template>
        </el-statistic>
      </el-col>
      <el-col :span="6">
        <el-statistic title="待业人数" :value="Math.round(animatedUnemployed)" />
      </el-col>
      <el-col :span="6">
        <el-statistic title="深造人数" :value="Math.round(animatedFurtherStudy)">
          <template #title>
            <el-tooltip
              effect="light"
              placement="top"
              content="深造率 = 深造人数 / 总毕业人数 × 100%"
            >
              <span>深造人数</span>
            </el-tooltip>
          </template>
          <template #suffix>
            <span class="rate-text">({{ animatedStudyRate.toFixed(2) }}%)</span>
          </template>
        </el-statistic>
      </el-col>
    </el-row>
  </div>

  <div class="graph_container" ref="chartRef">地图分布</div>
</template>

<style lang="scss" scoped>
.filter-bar {
  display: flex;
  gap: 15px;
  // margin-bottom: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;

  .filter-item {
    display: flex;
    align-items: center;

    .filter-label {
      color: #61666d;
      margin-right: 8px;
    }
  }
  .button-group {
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
}

.summary-text {
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  // margin-bottom: 20px;

  .highlight {
    color: #00aeec;
    font-weight: 600;
    font-size: 18px;
  }
}
.summary-container {
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;

  .el-statistic {
    padding: 10px;
    border-radius: 8px;
    background: #f8f9fa;

    :deep(.el-statistic__head) {
      font-size: 14px;
      color: #606266;
      margin-bottom: 8px;
    }

    :deep(.el-statistic__content) {
      font-size: 24px;
      font-weight: bold;
      color: #00aeec;
    }

    .rate-text {
      font-size: 14px;
      color: #909399;
      margin-left: 5px;
    }
  }
}

.graph_container {
  margin: 0 auto;
  padding: 15px;
  max-width: 1000px;
  border: 2px dashed #00aeec;
  border-radius: 8px;
  background: #fff;
  border-radius: 8px;
  min-height: 600px;
}
</style>
